﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using ThresholdAssistant.Autofac;
using ThresholdAssistant.DataContract.Result;
using ThresholdAssistant.Enums;
using ThresholdAssistant.NLogSdk;
using ThresholdAssistant.Tools.Extensions;
using ThresholdAssistant.WebAPI.Models;
using ThresholdAssistant.WebAPI.Models.Constants;
using ThresholdAssistant.WebAPI.Repository;

namespace ThresholdAssistant.WebAPI.Service
{
    /// <summary>
    /// 
    /// </summary>
    public class HuyiSmsService : BaseService, IBaseAutofac
    {

        public SendSmsRecordRepository SendSmsRecordRepository { get; set; }

        /// <summary>
        /// 发送短信
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public async Task<ContractResult> SendSmsAsync(SendSmsParam param)
        {
            if (param.SmsList.Any(e => string.IsNullOrWhiteSpace(e.Phone)) == true ||
                param.SmsList.Any(e => string.IsNullOrWhiteSpace(e.Title)) == true ||
                param.SmsList.Any(e => string.IsNullOrWhiteSpace(e.Name)) == true ||
                param.SmsList.Any(e => e.Value <= 0) == true)
            {
                return new ContractResult().SetError(ErrorResultEnum.InvalidParam);
            }

            if (param.SmsList?.Count() == 1)
            {
                return await SendSmsAsync(param.SmsList.First());
            }
            else
            {
                return await SendBatchSmsAsync(param.SmsList);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public async Task<ContractResult> SendSmsAsync(SmsInfoParam param)
        {
            var result = new ContractResult();
            var smsConfig = AppSettingConstant.HuyiSmsConfig;
            try
            {
                var postUrl = $"{smsConfig.SingleUrl}&account={smsConfig.ApiId}&password={smsConfig.ApiKey}&mobile={param.Phone}&templateid={smsConfig.TemplateId}&content={param.Name}|{param.Title}|{param.DateTime.ToString("yyyy-MM-dd HH:mm:ss")}|{param.Value}&format=json";
                var request = new HttpRequestMessage(HttpMethod.Get, postUrl);
                var rspRlt = await HttpClient.SendAsync(request);
                rspRlt.EnsureSuccessStatusCode();
                var response = await rspRlt.Content.ReadAsStringAsync();
                var apiResult = JsonConvert.DeserializeObject<HuyiSmsResponse>(response);
                await SendSmsRecordRepository.AddAsync(new SendSmsRecord
                {
                    Type = SmsTypeEnum.HuyiSms,
                    Source = SmsSourceEnum.Warn,
                    Phone = param.Phone,
                    TemplateId = smsConfig.TemplateId,
                    Status = apiResult.Code == 2 ? RecordStatusEnum.Success : RecordStatusEnum.Fail,
                    SmsId = apiResult.SmsId,
                    Message = response,
                    CreateTime = DateTime.Now,
                    UpdateTime = DateTime.Now,
                    Remark = ""
                });
                if (apiResult.Code == 2)
                {
                    return result.SetSuceccful();
                }
                else
                {
                    return result.SetError("-1", apiResult.Message);
                }
            }
            catch (Exception ex)
            {
                NLogUtil.Error($"发送短信异常:{ex}");
                return result.SetError(ErrorResultEnum.RequestApiFail);
            }
        }

        /// <summary>
        /// 批量发送短信
        /// </summary>
        /// <returns></returns>
        public async Task<ContractResult> SendBatchSmsAsync(IEnumerable<SmsInfoParam> param)
        {
            var result = new ContractResult();

            if (param == null || param.Any() == false)
            {
                return result.SetError("-1", "发送参数不能为空");
            }
            param = param.Where(x => string.IsNullOrEmpty(x.Phone) == false).ToList();
            if (param.Any() == false)
            {
                return result.SetError("-1", "无可发送内容");
            }

            var smsConfig = AppSettingConstant.HuyiSmsConfig;
            try
            {
                var request = new HttpRequestMessage(HttpMethod.Post, smsConfig.BatchUrl);
                var collection = new Dictionary<string, string>();
                collection.Add("account", smsConfig.ApiId);
                collection.Add("password", smsConfig.ApiKey);
                collection.Add("mobile", string.Join(",", param.Select(e => $"{e.Phone}|{e.Name}|{e.Title}|{e.DateTime.ToString("yyyy-MM-dd HH:mm:ss")}|{e.Value}")));
                collection.Add("templateid", smsConfig.TemplateId);
                collection.Add("format", "json");
                var content = new FormUrlEncodedContent(collection);
                request.Content = content;
                var rspRlt = await HttpClient.SendAsync(request);
                rspRlt.EnsureSuccessStatusCode();
                var response = await rspRlt.Content.ReadAsStringAsync();
                var apiResult = JsonConvert.DeserializeObject<HuyiSmsResponse>(response);
                var date = DateTime.Now;
                await SendSmsRecordRepository.AddAsync(param.Select(e => new SendSmsRecord
                {
                    Type = SmsTypeEnum.HuyiSms,
                    Source = SmsSourceEnum.Warn,
                    Phone = e.Phone,
                    TemplateId = smsConfig.TemplateId,
                    Status = apiResult.Code == 2 ? RecordStatusEnum.Success : RecordStatusEnum.Fail,
                    Message = response,
                    SmsId = apiResult.BatchId,
                    CreateTime = date,
                    UpdateTime = date,
                    Remark = ""
                }));
                if (apiResult.Code == 2)
                {
                    return result.SetSuceccful();
                }
                else
                {
                    return result.SetError("-1", apiResult.Message);
                }
            }
            catch (Exception ex)
            {
                NLogUtil.Error($"发送短信异常:{ex}");
                return result.SetError(ErrorResultEnum.RequestApiFail);
            }
        }

        /// <summary>
        /// 获取短信余量
        /// </summary>
        /// <returns></returns>
        public async Task<ContractResult<int>> GetSmsNumAsync()
        {
            var result = new ContractResult<int>();
            var smsConfig = AppSettingConstant.HuyiSmsConfig;
            try
            {
                var request = new HttpRequestMessage(HttpMethod.Post, smsConfig.SmsNumUrl);
                var collection = new Dictionary<string, string>();
                collection.Add("account", smsConfig.ApiId);
                collection.Add("password", smsConfig.ApiKey);
                collection.Add("format", "json");
                var content = new FormUrlEncodedContent(collection);
                request.Content = content;
                var rspRlt = await HttpClient.SendAsync(request);
                rspRlt.EnsureSuccessStatusCode();
                var response = await rspRlt.Content.ReadAsStringAsync();
                var apiResult = JsonConvert.DeserializeObject<HuyiSmsResponse>(response);
                return result.SetSuceccful(apiResult.Num);
            }
            catch (Exception ex)
            {
                NLogUtil.Error($"获取短信余量异常:{ex}");
                return result.SetError(ErrorResultEnum.RequestApiFail);
            }
        }

        /// <summary>
        /// 获取短信统计数据
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public async Task<ContractResult<SmsStatisticsData>> GetStatisticsAsync(GetStatisticsParam param)
        {
            var result = new ContractResult<SmsStatisticsData>();
            if (param.StartTime == null)
            {
                param.StartTime = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd"));
            }
            if (param.EndTime == null)
            {
                param.EndTime = Convert.ToDateTime(DateTime.Now.AddDays(1).ToString("yyyy-MM-dd"));
            }

            if (param.StartTime > param.EndTime)
            {
                var t = param.StartTime;
                param.StartTime = param.EndTime;
                param.EndTime = t;
            }
            var list = await SendSmsRecordRepository.GetStatisticsAsync(Convert.ToDateTime(param.StartTime?.ToString("yyyy-MM-dd")), Convert.ToDateTime(param.EndTime?.ToString("yyyy-MM-dd")));
            if (list?.Any() == true)
            {
                var lst = list.Select(e => new SmsStatisticsItemData
                {
                    SendDate = e.SendDate,
                    Type = e.Type.GetDescription(),
                    NumCount = e.NumCount,
                    SuccessCount = e.SuccessCount,
                    FailCount = e.FailCount
                }).ToList();
                result.Data = new SmsStatisticsData
                {
                    List = lst
                };
            }
            return result.SetSuceccful();
        }

        /// <summary>
        /// 发送语音消息
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public async Task<ContractResult> SendVoiceAsync(SmsInfoParam param)
        {
            var result = new ContractResult();
            var voiceConfig = AppSettingConstant.HuyiVoiceConfig;
            try
            {
                var postUrl = $"{voiceConfig.SingleUrl}&account={voiceConfig.ApiId}&password={voiceConfig.ApiKey}&mobile={param.Phone}&templateid={voiceConfig.TemplateId}&content={param.Name}|{param.Title}|{param.DateTime.ToString("yyyy-MM-dd HH:mm:ss")}|{param.Value}&format=json";
                var request = new HttpRequestMessage(HttpMethod.Get, postUrl);
                var rspRlt = await HttpClient.SendAsync(request);
                rspRlt.EnsureSuccessStatusCode();
                var response = await rspRlt.Content.ReadAsStringAsync();
                var apiResult = JsonConvert.DeserializeObject<HuyiVoiceResponse>(response);
                await SendSmsRecordRepository.AddAsync(new SendSmsRecord
                {
                    Type = SmsTypeEnum.HuyiVoice,
                    Source = SmsSourceEnum.Warn,
                    Phone = param.Phone,
                    TemplateId = voiceConfig.TemplateId,
                    Status = apiResult.Code == 2 ? RecordStatusEnum.Success : RecordStatusEnum.Fail,
                    SmsId = apiResult.VoiceId,
                    Message = response,
                    CreateTime = DateTime.Now,
                    UpdateTime = DateTime.Now,
                    Remark = ""
                });
                if (apiResult.Code == 2)
                {
                    return result.SetSuceccful();
                }
                else
                {
                    return result.SetError("-1", apiResult.Message);
                }

            }
            catch (Exception ex)
            {
                NLogUtil.Error($"发送语音异常:{ex}");
                return result.SetError(ErrorResultEnum.RequestApiFail);
            }
        }

        /// <summary>
        /// 获取语音余量
        /// </summary>
        /// <returns></returns>
        public async Task<ContractResult<int>> GetVoiceNumAsync()
        {
            var result = new ContractResult<int>();
            var voiceConfig = AppSettingConstant.HuyiVoiceConfig;
            try
            {
                var request = new HttpRequestMessage(HttpMethod.Post, voiceConfig.VoiceNumUrl);
                var collection = new Dictionary<string, string>();
                collection.Add("account", voiceConfig.ApiId);
                collection.Add("password", voiceConfig.ApiKey);
                collection.Add("format", "json");
                var content = new FormUrlEncodedContent(collection);
                request.Content = content;
                var rspRlt = await HttpClient.SendAsync(request);
                rspRlt.EnsureSuccessStatusCode();
                var response = await rspRlt.Content.ReadAsStringAsync();
                var apiResult = JsonConvert.DeserializeObject<HuyiVoiceResponse>(response);
                return result.SetSuceccful(apiResult.Num);
            }
            catch (Exception ex)
            {
                NLogUtil.Error($"获取语音余量异常:{ex}");
                return result.SetError(ErrorResultEnum.RequestApiFail);
            }
        }
    }
}
